package com.example.websocket.threadTest;

public class EnergySystem {

    private final double[] energyBox;

    private final Object lockObject = new Object();

    public EnergySystem(int n, double initialEnergy) {
        this.energyBox = new double[n];
        for (int i = 0; i < energyBox.length; i ++) {
            energyBox[i] = initialEnergy;
        }
    }

    public void transfer(int from, int to, double amount) {

//        if (energyBox[from] < amount) {
//            return;
//        }
//        System.out.println(Thread.currentThread().getName());
//        energyBox[from] -= amount;
//        System.out.printf("从%d转移%10.2f单位能量到%d", from, amount, to);
//        energyBox[to] += amount;
//        System.out.printf("能量总和：%10.2f%n", getTotalEnergies());
        synchronized (lockObject) {
            while (energyBox[from] < amount) {
                try {
                    lockObject.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(Thread.currentThread().getName());
            energyBox[from] -= amount;
            System.out.printf("从%d转移%10.2f单位能量到%d", from, amount, to);
            energyBox[to] += amount;
            System.out.printf("能量总和：%10.2f%n", getTotalEnergies());

            lockObject.notifyAll();
        }
    }

    private double getTotalEnergies() {
        double sum = 0;
        for (double amount : energyBox) {
            sum += amount;
        }
        return sum;
    }

    public int getBoxAmount() {
        return energyBox.length;
    }
}
